import { editor } from 'monaco-editor-core'

export function debounce (fn, n = 100) {
  let handle
  return (...args) => {
    if (handle) clearTimeout(handle)
    handle = setTimeout(() => {
      fn(...args)
    }, n)
  }
}

export function getOrCreateModel (
  uri,
  lang,
  value
) {
  const model = editor.getModel(uri)
  if (model) {
    model.setValue(value)
    return model
  }
  return editor.createModel(value, lang, uri)
}

export function asDisposable (disposables) {
  return { dispose: () => disposeAll(disposables) }
}

export function disposeAll (disposables) {
  while (disposables.length) {
    disposables.pop().dispose()
  }
}

export function createDisposable (cb) {
  return {
    dispose: cb
  }
}

export function normalizePath (path) {
  return path.replace(/\\/g, '/')
}

export const loadTheme = async (
  editor
) => {
  const themes = await import('../themes')
  return themes.loadTheme(editor)
}

export const loadGrammars = async (
  monaco,
  editor
) => {
  const grammars = await import('../grammars')
  return grammars.loadGrammars(monaco, editor)
}
